﻿using System;

using System.Threading;

namespace RFEngine.Threading
{
    public class EventTimer
    {
        #region Fields

        private object _SyncObject = new object();
        private bool _Completed;
        private bool _IsRunning;
        private volatile float _TimeOfEvent;

        private GameTimer _Timer;
        private Action _TimerCallback;

        #endregion

        /// <summary>
        /// Constructs a new instance of this object.
        /// </summary>
        /// <param name="timeofEvent">The amount of time in seconds before executing the TimerCallback</param>
        /// <param name="callback">The object to call when this timer has expired</param>
        public EventTimer(float timeofEvent, Action callback)
        {
            _TimeOfEvent = timeofEvent;
            _Timer = new GameTimer();
        }

        /// <summary>
        /// Method for starting the Timer.
        /// </summary>
        public void Start()
        {
            if (!_IsRunning && !_Completed)
            {
                _Timer.Start();
                _IsRunning = true;

                if (_Timer.ElapsedSeconds < _TimeOfEvent)
                {
                    ThreadPool.QueueUserWorkItem
                    (
                        delegate
                        {
                            while (!_Completed)
                            {
                                lock (_SyncObject)
                                {
                                    if (_TimeOfEvent < _Timer.ElapsedSeconds)
                                    {
                                        Thread.Sleep(1);
                                        continue;
                                    }

                                    _Timer.Stop();
                                    _Completed = true;
                                    _TimerCallback();
                                }
                            }
                        }
                    );
                }
            }
        }

        /// <summary>
        /// Method for stoping the Timer.
        /// </summary>
        public void Stop() 
        {
            _Timer.Stop();
            _IsRunning = false;
            _Completed = true;
        }

        /// <summary>
        /// Method for reseting the timer to zero.
        /// </summary>
        public void Reset() 
        {
            Stop();
            _Timer.Reset();            
            _Completed = false;
        }
    }
}
